
import { Menu } from "antd"
import React, { useContext, useState, useMemo, useEffect, useCallback } from "react"
import { useNavigate, matchPath, useLocation } from "react-router-dom"
     
import { layoutContext } from "../page"


function Sider() {
    const { flatedRoutes, routes } = useContext(layoutContext)

    const { pathname } = useLocation() // 获取路径

    const navigate = useNavigate()

    // 选中的菜单项
    // 包含当前路由与所有上级路由的 path
    const selectedMenus = useMemo(() => {
        const currentRoutes = flatedRoutes.filter((route) =>
            route.path
                ? matchPath(
                    {
                        path: pathname,
                        // 模糊匹配，包含上级
                        end: false,
                    },
                    route.path
                )
                : false
        )
        return currentRoutes.map((route) => route.path)
    }, [flatedRoutes, pathname])

    const [openKeys, setOpenKeys] = useState(selectedMenus)

    useEffect(() => {
        setOpenKeys(
            selectedMenus.map((route) => route.match(/^(\/[\w\d]+)\/?/)?.[1])
        )
    }, [selectedMenus])

    const renderMenus = (routes = []) => {
        return routes
            .filter(r => !r.hidden)
            .map(r => {
                if (r?.children?.filter(it => !it.hidden).length) {
                    // 根据 getItem 返回
                    return getItem(r.name, r.path, r.icon, renderMenus(r.children))
                }
                return getItem(r.name, r.path, r.icon, null, 'item')
            })
    }

    const onClickMenu = e => {
        console.log(e)
        navigate(e.key)
    }

    const handleOpenChange = openKeys => {
        setOpenKeys([openKeys[openKeys.length - 1]])
    }


    return (
        <>
            <div className="logo-vertical">搜索...</div>
            <Menu
                mode="inline"
                theme="dark"
                openKeys={openKeys}
                selectedKeys={selectedMenus}
                onOpenChange={handleOpenChange}
                items={renderMenus(routes)}
                onClick={onClickMenu}
            />
        </>
    )
}

export default Sider

function getItem(label, key, icon, children, type) {
    return {
        key,
        icon,
        children,
        label,
        type
    };
}